import { Image, InfiniteScroll, List } from "antd-mobile";
// mock数据
import { users } from "../users";
import { useState, useEffect } from "react";
import { ListRes, fetchListAPI } from "@/apis/list";

import { useNavigate } from 'react-router-dom'

type Props = {
  channelId: string
}

const HomeList = (props: Props) => {
  const { channelId } = props
  // 获取列表数据
  const [listRes, setListRes] = useState<ListRes>({
    results: [],
    pre_timestamp: '' + new Date().getTime(),
  });

  useEffect(() => {
    const getList = async () => {
      try {
        const res = await fetchListAPI({
          channel_id: channelId,
          timestamp: '' + new Date().getTime(),
        });

        setListRes({
          results: res.data.data.results,
          pre_timestamp: res.data.data.pre_timestamp,
        });
      } catch (error) {
        console.log("获取列表数据失败", error);
      }
    };

    getList();
  }, [channelId]);

  // 加载更多  标记是否还有新数据  实现上拉加载 hasMore为true 小于threshold
  const [hasMore,setHasMore] = useState(true)

  const loadMore = async () => {
    try {
      const res = await fetchListAPI({
        channel_id: channelId,
        timestamp: listRes.pre_timestamp,
      })

      // 停止监听
      if(res.data.data.results.length === 0){
        setHasMore(false)
      }

      setListRes({
        // 拼接新老列表数据  listRes.results 上次存放的旧数据
        results: [...listRes.results, ...res.data.data.results],
        // 重置时间参数 为下一次请求做准备
        pre_timestamp: res.data.data.pre_timestamp,
      })


    } catch (error) {
      console.log("上拉加载获取列表数据失败", error);
    }
  }


  // 路由跳转
  const navigate = useNavigate()
  const goToDetail = (art_id: string) => {
    navigate(`/detail?id=${art_id}`)
  }

  return (
    <>
      <List>
        {listRes.results.map((item) => (
          <List.Item
          onClick={()=> goToDetail(item.art_id)}
            key={item.art_id}
            prefix={
              <Image
                src={item.cover.images?.[0]}
                style={{ borderRadius: 20 }}
                fit="cover"
                width={40}
                height={40}
              />
            }
            description={item.pubdate}
          >
            {item.title}
          </List.Item>
        ))}
      </List>

      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={100} />
    </>
  );
};

export default HomeList;
